﻿using _698._45Tool.Utils;
using CommonServiceLocator;
using Communication;
using DocumentFormat.OpenXml.Drawing.Charts;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using Jn698._45GWTool.Communication;
using Jn698._45GWTool.Models.DataGrid;
using Jn698._45GWTool.Settings;
using nblTool.utils;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WebFirst.Entities;
using WindowsFormsApp1.Utils;

namespace Jn698._45GWTool.ViewModels
{
    public class RSDViewModel:ViewModelBase
    {
        private static SerialPortHelper serialPortHelper = SerialPortHelper.Instance;
        private static TcpHelper tcpHelper = TcpHelper.Instance;
        private static CancellationTokenSource cts;

        private static bool? state= cts?.Token.IsCancellationRequested;

        public bool? State
        {
            get { return state; }
            set
            {
                Set(ref state, value);
                
            }
        }

        private static int jobRelayTime;

        public int JobRelayTime
        {
            get { return jobRelayTime; }
            set { jobRelayTime = value; RaisePropertyChanged(); }
        }


        private string RSD;

        private string rsd1OAD;

        public string RSD1OAD
        {
            get { return rsd1OAD; }
            set { Set(ref rsd1OAD, value); }
        }

        private string rsd2OAD;

        public string RSD2OAD
        {
            get { return rsd2OAD; }
            set { Set(ref rsd2OAD, value); }
        }

        private string rsd1Data;

        public string RSD1Data
        {
            get { return rsd1Data; }
            set { Set(ref rsd1Data, value); }
        }

        private DateTime dateTimeP;

        public DateTime DateTimeP
        {
            get { return dateTimeP; }
            set { Set(ref dateTimeP, value); }
        }

        private DateTime rsd2DateTimeStartP;

        public DateTime RSD2DateTimeStartP
        {
            get { return rsd2DateTimeStartP; }
            set { Set(ref rsd2DateTimeStartP, value); }
        }

        private DateTime rsd2DateTimeEndP;

        public DateTime RSD2DateTimeEndP
        {
            get { return rsd2DateTimeEndP; }
            set { Set(ref rsd2DateTimeEndP, value); }
        }

        private DateTime rsd4DateTimeStartP;

        public DateTime RSD4DateTimeStartP
        {
            get { return rsd4DateTimeStartP; }
            set { Set(ref rsd4DateTimeStartP, value); }
        }

        private DateTime rsd5DateTimeStartP;

        public DateTime RSD5DateTimeStartP
        {
            get { return rsd5DateTimeStartP; }
            set { Set(ref rsd5DateTimeStartP, value); }
        }

        private DateTime rsd6DateTimeStartP;

        public DateTime RSD6DateTimeStartP
        {
            get { return rsd6DateTimeStartP; }
            set { Set(ref rsd6DateTimeStartP, value); }
        }
        private DateTime rsd6DateTimeEndP;

        public DateTime RSD6DateTimeEndP
        {
            get { return rsd6DateTimeEndP; }
            set { Set(ref rsd6DateTimeEndP, value); }
        }

        private string tiData;

        public string TIData
        {
            get { return tiData; }
            set { Set(ref tiData, value); }
        }


        private List<SingleData> tiList;

        public List<SingleData> TIList
        {
            get { return tiList; }
            set { Set(ref tiList, value); }
        }

        private int selectedRSD2TI;

        public int SelectedRSD2TI
        {
            get { return selectedRSD2TI; }
            set { Set(ref selectedRSD2TI, value); }
        }

        private int selectedRSD6TI;

        public int SelectedRSD6TI
        {
            get { return selectedRSD6TI; }
            set { Set(ref selectedRSD6TI, value); }
        }

        private string dateTimeStartRSD2;

        public string DateTimeStartRSD2
        {
            get { return dateTimeStartRSD2; }
            set { Set(ref dateTimeStartRSD2, value); }
        }

        private string dateTimeEndRSD2;

        public string DateTimeEndRSD2
        {
            get { return dateTimeEndRSD2; }
            set { Set(ref dateTimeEndRSD2, value); }
        }

        private string dataRSD2;

        public string DataRSD2
        {
            get { return dataRSD2; }
            set { Set(ref dataRSD2, value); }
        }

        private int dataRSD6;

        public int DataRSD6
        {
            get { return dataRSD6; }
            set { Set(ref dataRSD6, value); }
        }

        private int dataRSD9;

        public int DataRSD9
        {
            get { return dataRSD9; }
            set { Set(ref dataRSD9, value); }
        }

        private string headerName;

        public string HeaderName
        {
            get { return headerName; }
            set { Set(ref headerName,value); }
        }


        private ObservableCollection<MSData> values;

        public ObservableCollection<MSData> Values
        {
            get { return values; }
            set { Set(ref values,value); }
        }

        private bool userTypeVisibility;

        public bool UserTypeVisibility
        {
            get { return userTypeVisibility; }
            set { Set(ref userTypeVisibility,value); }
        }

        private bool userAddressVisibility;

        public bool UserAddressVisibility
        {
            get { return userAddressVisibility; }
            set { Set(ref userAddressVisibility, value); }
        }

        private bool configNumVisibility;

        public bool ConfigNumVisibility
        {
            get { return configNumVisibility; }
            set { Set(ref configNumVisibility, value); }
        }

        private bool userTypeRegionVisibility;

        public bool UserTypeRegionVisibility
        {
            get { return userTypeRegionVisibility; }
            set { Set(ref userTypeRegionVisibility, value); }
        }


        private ObservableCollection<RSD2Data> rsd2DataList;

        public ObservableCollection<RSD2Data> RSD2DataList
        {
            get { return rsd2DataList; }
            set { Set(ref rsd2DataList,value); }
        }

        #region ms
        private List<string> msList;

        public List<string> MSList
        {
            get { return msList; }
            set { Set(ref msList,value); }
        }

        private int selectedMS;

        public int SelectedMS
        {
            get { return selectedMS; }
            set { Set(ref selectedMS,value);SetZIndex(); }
        }


        private int selectedRSD4MS;

        public int SelectedRSD4MS
        {
            get { return selectedRSD4MS; }
            set { Set(ref selectedRSD4MS, value); }
        }

        private int selectedRSD5MS;

        public int SelectedRSD5MS
        {
            get { return selectedRSD5MS; }
            set { Set(ref selectedRSD5MS, value); }
        }

        private ObservableCollection<MSRegionData> msRegionDataList;

        public ObservableCollection<MSRegionData> MSRegionDataList
        {
            get { return msRegionDataList; }
            set { Set(ref msRegionDataList,value); }
        }

        private List<SingleData> unitList;

        public List<SingleData> UnitList
        {
            get { return unitList; }
            set { unitList = value; }
        }

        #endregion

        private void RSDInit()
        {
            try
            {
                switch (Convert.ToSByte(RSD.Substring(0, 2),16))
                {
                    case 1:
                        RSD1OAD = RSD.Substring(2, 8);
                        RSD1Data = RSD.Substring(10);
                        break;
                    case 2:
                        RSD2OAD = RSD.Substring(2, 8);
                        DateTimeStartRSD2 = RSD.Substring(10, 16);
                        DateTimeEndRSD2 = RSD.Substring(26, 16);
                        DataRSD2 = RSD.Substring(42);
                        SelectedRSD2TI = int.Parse(DataRSD2.Substring(2, 2));
                        TIData = Convert.ToInt16(DataRSD2.Substring(4, 4),16).ToString();
                        //TIData = int.Parse(DataRSD2.Substring(4, 4)).ToString();
                        break;
                    case 3:
                        for (int i = 0; i < int.Parse(RSD.Substring(2, 2)); i++)
                        {
                            RSD2Data rSD2Data = new RSD2Data
                            {
                                OAD = RSD.Substring(4 + i * (8 + 16 + 16 + 8), 8),
                                Start = RSD.Substring(12 + i * (8 + 16 + 16 + 8), 16),
                                End = RSD.Substring(28 + i * (8 + 16 + 16 + 8), 16),
                                TI = RSD.Substring(44 + i * (8 + 16 + 16 + 8), 8)
                            };
                            RSD2DataList.Add(rSD2Data);
                        }
                        break;
                    case 4:
                        RSD4DateTimeStartP = new DateTime(Convert.ToInt16(RSD.Substring(2, 4),16), Convert.ToInt16(RSD.Substring(6, 2),16), Convert.ToInt16(RSD.Substring(8, 2), 16)
                            , Convert.ToInt16(RSD.Substring(10, 2), 16), Convert.ToInt16(RSD.Substring(12, 2), 16), Convert.ToInt16(RSD.Substring(14, 2), 16));
                        //RSD4DateTimeStartP = new DateTime(year,month,day,hour,min,sec);
                        SelectedMS = int.Parse(RSD.Substring(16, 2));
                        MSInit(SelectedMS, RSD.Substring(16));
                        break;
                    case 5:
                        RSD5DateTimeStartP = new DateTime(Convert.ToInt16(RSD.Substring(2, 4), 16), Convert.ToInt16(RSD.Substring(6, 2), 16), Convert.ToInt16(RSD.Substring(8, 2), 16)
                            , Convert.ToInt16(RSD.Substring(10, 2), 16), Convert.ToInt16(RSD.Substring(12, 2), 16), Convert.ToInt16(RSD.Substring(14, 2), 16));
                        //RSD4DateTimeStartP = new DateTime(year,month,day,hour,min,sec);
                        SelectedMS = int.Parse(RSD.Substring(16, 2));
                        MSInit(SelectedMS, RSD.Substring(16));
                        break;
                    case 6:
                    case 7:
                    case 8:
                        RSD6DateTimeStartP = new DateTime(Convert.ToInt16(RSD.Substring(2, 4), 16), Convert.ToInt16(RSD.Substring(6, 2), 16), Convert.ToInt16(RSD.Substring(8, 2), 16)
                            , Convert.ToInt16(RSD.Substring(10, 2), 16), Convert.ToInt16(RSD.Substring(12, 2), 16), Convert.ToInt16(RSD.Substring(14, 2), 16));
                        RSD6DateTimeEndP = new DateTime(Convert.ToInt16(RSD.Substring(16, 4), 16), Convert.ToInt16(RSD.Substring(20, 2), 16), Convert.ToInt16(RSD.Substring(22, 2), 16)
                            , Convert.ToInt16(RSD.Substring(24, 2), 16), Convert.ToInt16(RSD.Substring(26, 2), 16), Convert.ToInt16(RSD.Substring(28, 2), 16));
                        SelectedRSD6TI = int.Parse(RSD.Substring(30, 2));
                        dataRSD6 = Convert.ToInt32(RSD.Substring(32, 4),16);
                        SelectedMS = int.Parse(RSD.Substring(36, 2));
                        MSInit(SelectedMS, RSD.Substring(36));
                        break;
                    case 9:
                        DataRSD9 = Convert.ToInt32(RSD.Substring(2, 2), 16);
                        break;
                    case 10:
                        DataRSD9 = Convert.ToInt32(RSD.Substring(2, 2), 16);
                        SelectedMS = int.Parse(RSD.Substring(4, 2));
                        MSInit(SelectedMS, RSD.Substring(4));
                        break;
                    case 0:
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            
        }
        /// <summary>
        /// ctor
        /// </summary>
        public RSDViewModel()
        {
            RSD = ServiceLocator.Current.GetInstance<EditRecordList>().StrRSD;
            this.dateTimeP = DateTime.Now;
            RSD2DateTimeEndP = DateTime.Now;
            RSD2DateTimeStartP = DateTime.Now;
            RSD4DateTimeStartP = DateTime.Now;
            RSD6DateTimeStartP = DateTime.Now;
            RSD6DateTimeEndP = DateTime.Now;
            //dataGrids.Columns.Clear();
            //dataGrids.Columns.Add(new DataGridTextColumn() { Header = "用户类型", Binding = new Binding("Name"),IsReadOnly=false }) ;
            /*TestValues = new[]
            {
                new {Name="za"},
                new{Name="ls"}
            };*/
            Values = new ObservableCollection<MSData>() {  };
            RSD2DataList=new ObservableCollection<RSD2Data>();
            HeaderName = "用户类型";

            TIList = new List<SingleData>() 
            {
             new SingleData { Name= "秒" },
             new SingleData { Name = "分" },
             new SingleData { Name = "时" },
             new SingleData { Name = "日" },
             new SingleData { Name = "月" },
             new SingleData { Name = "年" }
            };

            MSList = new List<string>() { "无电能表", "全部用户地址", "一组用户类型", "一组用户地址", "一组配置序号", "一组用户类型区间", "一组用户地址区间", "一组配置序号区间" };
            MSRegionDataList = new ObservableCollection<MSRegionData>();
            UnitList = new List<SingleData>() { 
                new SingleData { Name = "前闭后开" }, new SingleData { Name = "前开后闭" }, 
                new SingleData { Name = "前闭后闭" } ,new SingleData { Name = "前开后开" }
            };

            RSDInit();
        }


        /// <summary>
        /// 切换参数表格
        /// </summary>
        /// <param name="zIndexName"></param>
        private void SetZIndex()
        {
            Values.Clear();
            MSRegionDataList.Clear();
            UserTypeVisibility = false;
            UserAddressVisibility = false;
            ConfigNumVisibility = false;
            UserTypeRegionVisibility = false;
            switch (SelectedMS)
            {
                case 2:
                    UserTypeVisibility = true;
                    break;
                case 3:
                    UserAddressVisibility = true;
                    break;
                case 4:
                    ConfigNumVisibility = true;
                    break;
                case 5:
                case 6:
                case 7:
                    UserTypeRegionVisibility = true;
                    break;
                case 0:
                case 1:
                default:
                    break;
            }

        }

        private void MSInit(int index, string MSData)
        {
            int point;
            SetZIndex();
            switch (index)
            {
                case 4:
                    for (int i = 0; i < int.Parse(MSData.Substring(2, 2)); i++)
                    {
                        MSData mSData = new MSData { data = Convert.ToByte(MSData.Substring(4 + 4 * i, 4), 16).ToString() };
                        Values.Add(mSData);
                    }
                    break;
                case 2:
                    for (int i = 0; i < int.Parse(MSData.Substring(2, 2)); i++)
                    {
                        MSData mSData = new MSData { data = Convert.ToByte(MSData.Substring(4 + 2 * i, 2), 16).ToString() };
                        Values.Add(mSData);
                    }
                    break;
                case 3:
                    point = 4;
                    for (int i = 0; i < int.Parse(MSData.Substring(2, 2)); i++)
                    {
                        
                        int TSAlen = int.Parse(MSData.Substring(point, 2));
                        MSData mSData = new MSData { data = MSData.Substring(point+4, (TSAlen-1)*2) };
                        Values.Add(mSData);
                        point += 2+TSAlen*2;
                    }
                    break;
                case 5:
                    for (int i = 0; i < int.Parse(MSData.Substring(2, 2)); i++)
                    {
                        MSRegionData mSRegionData = new MSRegionData
                        {
                            Unit = GetMSRegionUnit(int.Parse(MSData.Substring(4 + 6 * i, 2))),
                            Start = Convert.ToInt16(MSData.Substring(6 + 6 * i, 2),16).ToString(),
                            End = Convert.ToInt16(MSData.Substring(8 + 6 * i, 2),16).ToString()
                        };
                        MSRegionDataList.Add(mSRegionData);
                    }
                    break;
                case 6:
                    point = 4;
                    for (int i = 0; i < int.Parse(MSData.Substring(2, 2)); i++)
                    {
                        string startData = "";
                        string endData = "";
                        string unitData = GetMSRegionUnit(int.Parse(MSData.Substring(point, 2)));
                        point += 2;
                        int TSAlen = int.Parse(MSData.Substring(point, 2));
                        startData = MSData.Substring(point + 4, (TSAlen - 1) * 2);
                        point += 2 + TSAlen * 2;
                        TSAlen = int.Parse(MSData.Substring(point, 2));
                        endData = MSData.Substring(point + 4, (TSAlen - 1) * 2);
                        point += 2 + TSAlen * 2;
                        MSRegionData mSRegionData = new MSRegionData
                        {
                            Unit = unitData,
                            Start = startData,
                            End = endData
                        };
                       
                        MSRegionDataList.Add(mSRegionData);
                    }
                    break;
                case 7:
                    for (int i = 0; i < int.Parse(MSData.Substring(2, 2)); i++)
                    {
                        MSRegionData mSRegionData = new MSRegionData
                        {
                            Unit = GetMSRegionUnit(int.Parse(MSData.Substring(4 + 10 * i, 2))),
                            Start = Convert.ToInt16(MSData.Substring(6 + 10 * i, 4), 16).ToString(),
                            End = Convert.ToInt16(MSData.Substring(10 + 10 * i, 4), 16).ToString()
                        };
                        MSRegionDataList.Add(mSRegionData);
                    }
                    break;
                case 0:
                case 1:
                default:
                    break;
            }
        }

        public string GetMSInfo()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(SelectedMS.ToString("X2"));
            switch (SelectedMS)
            {
                case 4:
                    stringBuilder.Append(Values.Count.ToString("X2"));
                    for (int i = 0; i < Values.Count; i++)
                    {
                        MSData mSData = Values[i];
                        try
                        {
                            stringBuilder.Append(int.Parse(mSData.data).ToString("X4"));
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message);
                            break;
                        }

                    }
                    break;
                case 2:
                    stringBuilder.Append(Values.Count.ToString("X2"));
                    for (int i = 0; i < Values.Count; i++)
                    {
                        MSData mSData = Values[i];
                        try
                        {
                            stringBuilder.Append(int.Parse(mSData.data).ToString("X2"));
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message);
                            break;
                        }
                        
                    }
                    break;
                case 3:
                    stringBuilder.Append(Values.Count.ToString("X2"));
                    for (int i = 0; i < Values.Count; i++)
                    {
                        MSData mSData = Values[i];
                        try
                        {
                            if (mSData.data.Length%2!=0)
                            {
                                mSData.data = mSData.data.PadLeft(mSData.data.Length+1,'0');
                            }
                            stringBuilder.Append((mSData.data.Length/2+1).ToString("X2"));
                            stringBuilder.Append((mSData.data.Length / 2 + -1).ToString("X2"));
                            stringBuilder.Append(mSData.data);
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message);
                            break;
                        }

                    }
                    break;
                case 5:
                    stringBuilder.Append(MSRegionDataList.Count.ToString("X2"));
                    for (int i = 0; i < MSRegionDataList.Count; i++)
                    {
                        MSRegionData mSRegionData = MSRegionDataList[i];

                        switch (mSRegionData.Unit)
                        {
                            case "前闭后开":
                                stringBuilder.Append("00");
                                break;
                            case "前开后闭":
                                stringBuilder.Append("01");
                                break;
                            case "前闭后闭":
                                stringBuilder.Append("02");
                                break;
                            case "前开后开":
                                stringBuilder.Append("03");
                                break;
                            default:
                                break;
                        }
                        stringBuilder.Append(int.Parse(mSRegionData.Start).ToString("X2"));
                        stringBuilder.Append(int.Parse(mSRegionData.End).ToString("X2"));
                    }
                    break;
                case 6:
                    stringBuilder.Append(MSRegionDataList.Count.ToString("X2"));
                    for (int i = 0; i < MSRegionDataList.Count; i++)
                    {
                        MSRegionData mSRegionData = MSRegionDataList[i];

                        switch (mSRegionData.Unit)
                        {
                            case "前闭后开":
                                stringBuilder.Append("00");
                                break;
                            case "前开后闭":
                                stringBuilder.Append("01");
                                break;
                            case "前闭后闭":
                                stringBuilder.Append("02");
                                break;
                            case "前开后开":
                                stringBuilder.Append("03");
                                break;
                            default:
                                break;
                        }
                        stringBuilder.Append((mSRegionData.Start.Length / 2 + 1).ToString("X2"));
                        stringBuilder.Append((mSRegionData.Start.Length / 2 + -1).ToString("X2"));
                        stringBuilder.Append(mSRegionData.Start);
                        stringBuilder.Append((mSRegionData.End.Length / 2 + 1).ToString("X2"));
                        stringBuilder.Append((mSRegionData.End.Length / 2 + -1).ToString("X2"));
                        stringBuilder.Append(mSRegionData.End);
                        
                    }
                    break;
                case 7:
                    stringBuilder.Append(MSRegionDataList.Count.ToString("X2"));
                    for (int i = 0; i < MSRegionDataList.Count; i++)
                    {
                        MSRegionData mSRegionData = MSRegionDataList[i];
                        
                        switch (mSRegionData.Unit)
                        {
                            case "前闭后开":
                                stringBuilder.Append("00");
                                break;
                            case "前开后闭":
                                stringBuilder.Append("01");
                                break;
                            case "前闭后闭":
                                stringBuilder.Append("02");
                                break;
                            case "前开后开":
                                stringBuilder.Append("03");
                                break;
                            default:
                                break;
                        }
                        stringBuilder.Append(int.Parse(mSRegionData.Start).ToString("X4"));
                        stringBuilder.Append(int.Parse(mSRegionData.End).ToString("X4"));
                    }
                    break;
                case 0:
                case 1:
                default:
                    break;
            }
            return stringBuilder.ToString();
        }
        private string GetMSRegionUnit(int index)
        {
            switch (index)
            {
                case 0:
                    return "前闭后开";
                case 1:return "前开后闭";
                case 2:return "前闭后闭";
                case 3:return "前开后开";
                default:
                    return "";
            }
        }
        #region  command
        public RelayCommand DateTimeToHESCommand
        {
            get
            {
                var command = new RelayCommand(() =>
                {
                    //Console.WriteLine(StringUtils.DateTime2String(DateTimeP));
                    RSD1Data = "1C"+ StringUtils.DateTime2String(DateTimeP);
                });
                return command;
            }
        }

        public RelayCommand DateTimeStartRSD2ToHESCommand
        {
            get
            {
                var command = new RelayCommand(() =>
                {
                    
                    DateTimeStartRSD2 = "1C" + StringUtils.DateTime2String(RSD2DateTimeStartP);
                });
                return command;
            }
        }

        public RelayCommand DateTimeEndRSD2ToHESCommand
        {
            get
            {
                var command = new RelayCommand(() =>
                {

                    DateTimeEndRSD2 = "1C" + StringUtils.DateTime2String(RSD2DateTimeEndP);
                });
                return command;
            }
        }

        public RelayCommand DataRSD2ToHESCommand
        {
            get
            {
                var command = new RelayCommand(() =>
                {
                    if (string.IsNullOrWhiteSpace(TIData))
                    {
                        MessageBox.Show("请输入数据");
                        return;
                    }
                    string temp;
                    temp = "54";
                    temp += string.Format("{0:X2}",SelectedRSD2TI);
                    temp += string.Format("{0:X4}", Int16.Parse(TIData));
                    DataRSD2 = temp;
                });
                return command;
            }
        }

       

        public RelayCommand StartTestJobCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    if (MainViewModel.selectedDevice == null)
                    {
                        MessageBox.Show("请选择设备");
                        return;
                    }

                    SendModule.SecuritySelectedIndex = ServiceLocator.Current.GetInstance<MainViewModel>().SecuritySelectedIndex;
                    switch (SendModule.SecuritySelectedIndex)
                    {

                        //明文+RN_MAC
                        case 2:
                        //明文+SID_MAC
                        case 3:
                        //密文+SID
                        case 4:
                        //密文+SID_MAC
                        case 5:
                            if (string.IsNullOrWhiteSpace(SendModule.SessionInitKey))
                            {
                                MessageBox.Show("请先建立应用连接");
                                return;
                            }
                            break;
                        //明文
                        case 0:
                        //明文+RN
                        case 1:
                        default:

                            break;
                    }
                    cts = new CancellationTokenSource();
                    State = false;
                    Task.Run(async () =>
                    {
                        while (true)
                        {
                            if (cts.IsCancellationRequested)
                            {
                                break;
                            }
                            


                            string frame = "";
                            string UserData = "";
                            byte[] byteAddress = StringUtils.strToHexByte(MainViewModel.selectedDevice.DeviceAddress);
                            List<byte> APDU;
                            UserData = "050300";
                            var vm = ServiceLocator.Current.GetInstance<RecordChoiceViewModel>();

                            UserData += vm.OAD;
                            UserData += "06";
                            UserData += StringUtils.DateTime2String(RSD6DateTimeStartP);
                            UserData += StringUtils.DateTime2String(RSD6DateTimeEndP);
                            UserData += SelectedRSD6TI.ToString("X2");
                            UserData += DataRSD6.ToString("X4");
                            UserData += GetMSInfo();

                            RCSDDataModel rCSDDataModel;

                            UserData += vm.RcsdDataList.Count.ToString("X2");
                            for (int i = 0; i < vm.RcsdDataList.Count; i++)
                            {
                                rCSDDataModel = vm.RcsdDataList[i];
                                if (rCSDDataModel.CSD == "对象属性描述符")
                                {
                                    UserData += "00";
                                }
                                else
                                {
                                    UserData += "01";
                                }
                                UserData += rCSDDataModel.Data;
                            }
                            /*if (IsCheck || RecordDataList.Count == 1)
                            {
                                if (index >= RecordDataList.Count)
                                {
                                    return;
                                }
                                var recordData = RecordDataList[index];
                                UserData = "050300" + recordData.StrOAD + recordData.StrRSD + recordData.StrRCSD;
                            }
                            else
                            {
                                UserData = "050400" + RecordDataList.Count.ToString("X2");
                                UserData += string.Join(",", RecordDataList.Select(item => item.StrOAD + item.StrRSD + item.StrRCSD)).Replace(",", "");
                            }*/
                            if (TerminalSettings.Instanse.TimeTagFlag)
                            {
                                UserData += "01";
                                UserData += StringUtils.DateTime2String(DateTime.Now);
                                UserData += TerminalSettings.Instanse.TimeTagData;

                            }
                            else
                            {
                                UserData += "00";
                            }
                            APDU = MessageGenerationModule.GetSecuriityFrame(StringUtils.hexStringToBytes(UserData.Replace(" ", string.Empty)).ToList(), SendModule.SecuritySelectedIndex);
                            //定义临时字节列表
                            List<byte> temp = new List<byte>();

                            temp.Add(0x68);
                            //长度域
                            short length = (short)(2 + 1 + 1 + (short)byteAddress.Length + 1 + 2 + (short)APDU.Count + 2);
                            //FrameLen = string.Format("{0:X2}{1:X2}", length & 0x00ff, length >> 8);
                            byte[] byteLength = BitConverter.GetBytes(length);

                            temp.AddRange(byteLength);

                            //控制域

                            //byte control = StringUtils.string_2_BCD(Control)[0];
                            temp.Add(0x43);

                            //地址域
                            //服务器地址SA
                            byte addressLen = (byte)(byteAddress.Length - 1);
                            if (MainViewModel.selectedDevice.DeviceAddress.Contains("A") || MainViewModel.selectedDevice.DeviceAddress.Contains("a"))
                            {
                                addressLen |= 0x40;
                            }
                            switch (TerminalSettings.Instanse.LogicAddressSelected)
                            {
                                case 1:
                                    addressLen |= 0x10;
                                    break;
                                case 2:
                                    addressLen |= 0x20;
                                    break;
                                case 3:
                                    addressLen |= 0x30;
                                    break;
                                case 0:
                                default:
                                    break;
                            }
                            //temp.Add((byte)(byteAddress.Length - 1));
                            temp.Add(addressLen);
                            Array.Reverse(byteAddress);
                            temp.AddRange(byteAddress);

                            //客户机地址CA
                            byte ca = 0x11;
                            temp.Add(ca);

                            //帧头校验HCS
                            //HCS = ByteUtils.bytesToHexString(CheckSum.CRC16(temp, 1));
                            temp.AddRange(CheckSum.CRC16(temp, 1));

                            //链路用户数据
                            temp.AddRange(APDU);

                            //帧校验FCS
                            //FCS = ByteUtils.bytesToHexString(CheckSum.CRC16(temp, 1));
                            temp.AddRange(CheckSum.CRC16(temp, 1));

                            //结束字符
                            temp.Add(0x16);
                            frame = ByteUtils.bytesToHexString(temp);


                            byte[] b = StringUtils.hexStringToBytes(frame);
                            string msgStr = "";
                            for (int i = 0; i < b.Length; i++)
                            {
                                msgStr += b[i].ToString("X2") + " ";
                            }
                            Messenger.Default.Send<string>($"发送帧({DateTime.Now.ToString()})：{msgStr}", "SendMessage");
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    //Task.Run(() => serialPortHelper.DataReceiveFunction());
                                    serialPortHelper.DataReceiveFunction();
                                    break;
                                case "GPRS":
                                    tcpHelper.SendData(MainViewModel.selectedDevice.DeviceAddress, b);
                                    break;
                                default:
                                    break;
                            }
                            try
                            {
                                await Task.Delay(TimeSpan.FromSeconds(JobRelayTime), cts.Token);
                            }
                            catch (OperationCanceledException)
                            {
                                Console.WriteLine("Task was cancelled.");
                                
                            }

                        }
                        
                    });
                    /* try
                     {

                     }
                     catch (OperationCanceledException)
                     {
                         Console.WriteLine("Task was cancelled.");
                     }
                     catch(Exception)
                     {
                         Console.WriteLine("Task was cancelled.");
                     }*/
                });
            }
        }

        public RelayCommand StopTestJobCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    cts?.Cancel();
                    State = true;
                });
            }
        }
        #endregion
    }
    public class MSData
    {
        public string data { get; set; }
    }
}
